import os, os.path
import random
import string

import cherrypy
import matasks
import maLogger

import aiygoogle

import sys

mytask = matasks.MaTasks()

class WebPage(object):
    @cherrypy.expose
    def index(self):
        return open(matasks.file_path+'/index.html')

@cherrypy.expose
class RefreshTimeService(object):
    def POST(self):
        return mytask.getSetting()

@cherrypy.expose
class WebPageService(object):

    @cherrypy.tools.accept(media='text/plain')
    def GET(self):
        return cherrypy.session['mystring']

    def POST(self, startTime='', stopTime=''):
        cherrypy.session['mystring'] = 'OK'
        if(startTime != '' and startTime != ''):
            mytask.setTime(startTime, stopTime)
            return 'OK'

    def PUT(self, another_string):
        cherrypy.session['mystring'] = another_string

    def DELETE(self):
        cherrypy.session.pop('mystring', None)

if __name__ == '__main__':
    maLogger.initLogger()
    mymission = aiygoogle.AiyMission()
    mytask.registerTask(mymission.do, 'do')
    mytask.registerTask(mymission.stop, 'stop')
    mytask.begin()
    conf = {
        '/': {
            'tools.sessions.on': True,
            'tools.staticdir.root': os.path.abspath(os.getcwd())
        },
        '/generator': {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
            'tools.response_headers.on': True,
            'tools.response_headers.headers': [('Content-Type', 'text/plain')],
        },
        '/refresh': {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
            'tools.response_headers.on': True,
            'tools.response_headers.headers': [('Content-Type', 'text/plain')],
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': matasks.file_path+'/public'
        }
    }
    webapp = WebPage()
    webapp.generator = WebPageService()
    webapp.refresh = RefreshTimeService()
    cherrypy.config.update({'server.socket_host': '0.0.0.0',
                            'server.socket_port': 19002})
    cherrypy.quickstart(webapp, '/', conf)
